package com.pet.server.ext.util;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.client.params.CookiePolicy;

import com.pet.server.ext.ApiResponse;
import com.pet.server.ext.Logger;

import net.sf.json.JSONObject;

public class CallApi {

	public static Logger logger = Logger.getLogger(CallApi.class);
	
	public static ApiResponse call(String url,Map<String, String> map,String cookie){
		ApiResponse response = new ApiResponse();
		postFromUrl(url, map,cookie,response);
        return response;
	}
	
	
	public static String postFromUrl(String url,Map<String, String> map,String cookie,ApiResponse response){
		if(map!=null){
			NameValuePair[] ps =new NameValuePair[map.size()];
			int i=0;
			StringBuffer sbuf =new StringBuffer();
			boolean b = true;
			for(Entry<String, String> e:map.entrySet()){
				NameValuePair p = new NameValuePair();
				p.setName(e.getKey());
				p.setValue(e.getValue());
				sbuf.append(b?(e.getKey()+"="+e.getValue()):("&"+e.getKey()+"="+e.getValue()));
				if(b){b=false;}
				ps[i]=p;
				i++;
			}
			logger.logInfo("send url:"+url+"?"+sbuf.toString());
			postFromURL(url, ps,cookie,response);
		}else{
			logger.logInfo("Array of parameters may not be null");
		}
		return null;
	}
	
	public static void postFromURL(String url, NameValuePair[] msg,String cookie,ApiResponse response ) {
		logger.logInfo("send post url  :"+url);
		String strURL = url;
		String result = null;
		PostMethod post = null;
		try {
			post = new PostMethod(strURL);
			post.setRequestBody(msg);
			post.getParams().setParameter("http.protocol.cookie-policy",CookiePolicy.BROWSER_COMPATIBILITY);
			HttpClient httpclient = new HttpClient();
			httpclient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
			if(cookie!=null){
				post.addRequestHeader("Cookie",cookie);
			}
			httpclient.executeMethod(post);
			if (post.getStatusCode() == HttpStatus.SC_OK) {
					Cookie[] cookies = httpclient.getState().getCookies();
					response.setCookies(cookies);
				//post.get
				result = post.getResponseBodyAsString();
			} else {
				result = post.getStatusLine().toString();
			}
		} catch (Exception e) {
			logger.logInfo("postFromURL Error!" + e.getMessage());
		} finally {
			post.releaseConnection();
		}
		logger.logInfo("send response  :"+result);
		response.setRet(parseJsonObj(result));
		//return result;
	}
	private static JSONObject parseJsonObj(String jsonStr){
		 try{
	        	return JSONObject.fromObject(jsonStr);
	        }catch(Exception e){
	        	return new JSONObject();
	        }
	}
	
}
